package best.driver.android.Activity.Login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import best.driver.android.*;
import best.driver.android.Activity.Base.BaseActivity;
import best.driver.android.Activity.Environment.EnvironmentActivity;
import best.driver.android.Activity.Register.CheckHintActivity;
import best.driver.android.Beans.LoginInfo;
import best.driver.android.Listener.VerifycodeReceiver;
import best.driver.android.Utils.Logger;
import best.driver.android.Utils.LoginCallback;
import best.driver.android.Utils.SmsSender;
import best.driver.android.Utils.Utils;
import best.driver.android.Utils.actions.Action1;
import best.driver.android.View.CanClearEditText;
import best.driver.android.common.app.AppProxy;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.*;
import best.driver.android.manager.UserInfoManager;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 登录界面
 */
public class Login extends BaseActivity implements VerifycodeReceiver.VerifycodeListener {

    private static final int WAITING_TIME = 60;
    private static final int SMS_LOGIN_REQ_CODE = 0;
    long mExitTime;

    @InjectView(R.id.btn_set_environment)
    Button mBtnSetEnvironment;

    @InjectView(R.id.edt_phone)
    CanClearEditText mEdtPhone;

    @InjectView(R.id.edt_verifycode)
    CanClearEditText mEdtVerifycode;

    @InjectView(R.id.btn_get_verifycode)
    Button mBtnGetVerifyCode;

    @InjectView(R.id.btn_login)
    Button mBtnLogin;

    @InjectView(R.id.tv_no_verifycode)
    TextView mTvNoVerifycode;

    @OnClick(R.id.btn_set_environment)
    protected void setEnvironment() {
        Intent intent = new Intent(this, EnvironmentActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.btn_get_verifycode)
    protected void getVerifyCode() {
        String phone = mEdtPhone.getText().toString().trim();
        if (!checkPhone(phone)) {
            return;
        }
        mBtnGetVerifyCode.setEnabled(false);
        showWaiting("正在验证");
        startTimer(1000);
        ApiStringRequest request = RequestFactory.creatPreloginRequest(phone, false);
        request.setListener(new ApiRequest.ApiRequestListener<String>() {
            @Override
            public void onRequestSuccess(String response) {
                if(!TextUtils.isEmpty(response)) {
                    AppInfo.showToast(Login.this, response);
                }
                hideWaiting();
            }

            @Override
            public void onRequestError(BestError error) {
                stopTimer();
                mBtnGetVerifyCode.setEnabled(true);
                mBtnGetVerifyCode.setText("验证");
                String phone = mEdtPhone.getText().toString().trim();
                if(!TextUtils.isEmpty(phone) && phone.length() == 11) {
                    mBtnGetVerifyCode.setBackgroundResource(R.drawable.login_btn_border_red);
                } else {
                    mBtnGetVerifyCode.setBackgroundResource(R.drawable.login_btn_border_gray);
                    mBtnGetVerifyCode.setEnabled(false);
                }
                hideWaiting();
                if(error instanceof BestApiError) {
                    AppInfo.showToast(Login.this, ((BestApiError) error).getErrorMessage());
                }
            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        Utils.hideKeyboard(this);
    }

    @OnClick(R.id.btn_login)
    protected void login() {
        mBtnLogin.setEnabled(false);
        String phone = mEdtPhone.getText().toString().trim();
        String verifycode = mEdtVerifycode.getText().toString().trim();
        //UserStatusManager.setLoginPhone(phone);

        if (!checkPhone(phone)) {
            mBtnLogin.setEnabled(true);
            return;
        }
        if (!checkVerifycode(verifycode)) {
            mBtnLogin.setEnabled(true);
            return;
        }

        showWaiting("正在登录");
        ApiObjectRequest<LoginInfo> request = RequestFactory.createLoginRequest("1", phone, verifycode);
        request.setListener(new ApiRequest.ApiRequestListener<LoginInfo>() {
            @Override
            public void onRequestSuccess(LoginInfo response) {
                hideWaiting();
                UserInfoManager.getInstance().setLogin(true);
                UserInfoManager.getInstance().setToken(response.accessToken);
                UserInfoManager.getInstance().setDriverId(response.driverId);
                startActivity(new Intent(Login.this, CheckHintActivity.class));
            }

            @Override
            public void onRequestError(BestError error) {
                hideWaiting();
                if(error instanceof BestApiError) {
                    AppInfo.showToast(Login.this, ((BestApiError) error).getErrorMessage());
                }
            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
//
    }

    private Timer mTimer;
    private TimerTask mTimerTask;
    private int mWaitingSeconds = WAITING_TIME;

    private String mSmsLimit;//失效时间
    private String mSmsChannel;
    private String mSmsContent;
    private Integer mSmsTimeCount = 0;
    private Timer mLoginStatusTimer;
    private TimerTask mLoginStatusTask;
    private Handler mLoginStatusHander = new Handler();

    private VerifycodeReceiver smsContentObserver;

    public static void start(Context context, Runnable loginCallback) {
        Intent target = new Intent();
        target.setClass(context, Login.class);
        context.startActivity(target);
        LoginCallback.setCallback(loginCallback);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_login);
        ButterKnife.inject(this, view);
        mEdtPhone.setIsOnlyNumber(true, 11);
        setTopTopic("验证手机");
        initViewAfter();
        setTopLineVisible(false);
        registerVerifyCodeReceiver();
        if(BuildConfig.DEBUG) {
            mBtnSetEnvironment.setVisibility(View.VISIBLE);
        }
    }

    private void registerVerifyCodeReceiver() {
        smsContentObserver = new VerifycodeReceiver(this, mHandler);
        smsContentObserver.setListener(this);
        Uri smsUri = Uri.parse("content://sms");
        getContentResolver().registerContentObserver(smsUri, true, smsContentObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
        stopLoginStatus();
        getContentResolver().unregisterContentObserver(smsContentObserver);
        SmsSender.release(Login.this);
        LoginCallback.setCallback(null);
    }

    private void initViewAfter() {
        initTextEvent();
        TelephonyManager phoneMgr=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
        String phone = phoneMgr.getLine1Number();
        if(phone != null) {
            if((phone.startsWith("+86") || phone.startsWith("+82")) && phone.length()>3) {
                phone = phone.substring(3, phone.length());
            }
            //韩国电话号码，如果是10位并且“1”开头，前面加0
            if (phone.length() == 10 && phone.startsWith("1")) {
                phone = "0" + phone;
            }
            mEdtPhone.setText(phone);
        }
        Logger.d("number:", "phoneMgr.getLine1Number() = " + phoneMgr.getLine1Number());
        Utils.showKeyboard(this, mEdtPhone.getEditText());
    }

    private void initTextEvent() {

        mEdtVerifycode.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().matches("^\\d{4}$") && s.toString().length() == 4 &&
                        !TextUtils.isEmpty(mEdtPhone.getText().toString()) && mEdtPhone.getText().toString().length() == 11) {
                    mBtnLogin.setEnabled(true);
                    mBtnLogin.setBackgroundResource(R.drawable.login_btn_border_red);
                    mBtnLogin.setTextColor(getColor(R.color.white));
                } else {
                    mBtnLogin.setEnabled(false);
                    mBtnLogin.setBackgroundResource(R.drawable.login_btn_border_gray);
                    mBtnLogin.setTextColor(getColor(R.color.c666));
                }
            }
        });

        mEdtPhone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                stopTimer();
                mBtnGetVerifyCode.setText(getString(R.string.get_verifycode));
                mWaitingSeconds = WAITING_TIME;
                if (s.toString().matches("^\\d{11}$")) {
                    mBtnGetVerifyCode.setEnabled(true);
                    mBtnGetVerifyCode.setBackgroundResource(R.drawable.login_btn_border_red);
                    mBtnGetVerifyCode.setTextColor(getColor(R.color.white));
                    if(!TextUtils.isEmpty(mEdtVerifycode.toString()) && mEdtVerifycode.getText().toString().length() == 4) {
                        mBtnLogin.setEnabled(true);
                        mBtnLogin.setBackgroundResource(R.drawable.login_btn_border_red);
                        mBtnLogin.setTextColor(getColor(R.color.white));
                    }
                } else {
                    mBtnGetVerifyCode.setEnabled(false);
                    mBtnGetVerifyCode.setBackgroundResource(R.drawable.login_btn_border_gray);
                    mBtnGetVerifyCode.setTextColor(getColor(R.color.c666));
                    mBtnLogin.setEnabled(false);
                    mBtnLogin.setBackgroundResource(R.drawable.login_btn_border_gray);
                    mBtnLogin.setTextColor(getColor(R.color.c666));
                }

            }
        });
    }

    @Override
    public void onReceiveVerifycode(final String verifycode) {
        Logger.d("USER", "verify code:" + verifycode);
        stopTimer();
        mWaitingSeconds = WAITING_TIME;
        mBtnGetVerifyCode.setText(getString(R.string.get_verifycode));
        mEdtVerifycode.setText(verifycode);
        //login();
    }


//    private void smsLogin() {
//        String phone = edtPhone.getText().toString().trim();
//        Intent intent = new Intent(this,LoginPhoneConfirm.class);
//        intent.putExtra("phone",phone);
//        startActivityForResult(intent, SMS_LOGIN_REQ_CODE);
//    }

    private boolean checkPhone(String phoneNum) {
        if (phoneNum.matches("^\\d{11,11}$")) {
            return true;
        } else {
            //AppInfo.showToast(this, getString(R.string.input_correct_phone));
            return false;
        }
    }

    private boolean checkVerifycode(String verifycode) {
        if (verifycode.matches("^\\d{4}$")) {
            return true;
        } else {
            //AppInfo.showToast(this, getString(R.string.input_correct_code));
            return false;
        }
    }

    private void loginStatus() {
        String phone = mEdtPhone.getText().toString().trim();
    }

    public void startLoginStatus() {
        stopLoginStatus();
        showWaiting();
        mSmsTimeCount = 0;
        mLoginStatusTimer = new Timer("MARQUEE");
        mLoginStatusTask = new TimerTask() {
            @Override
            public void run() {
                mLoginStatusHander.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mSmsTimeCount * 5 >= Integer.valueOf(mSmsLimit)){
                            AppInfo.showToast(Login.this, "短信登录失败，请重新发送");
                            stopLoginStatus();
                        }else{
                            loginStatus();
                        }
                        mSmsTimeCount ++;
                    }
                });
            }
        };
        mLoginStatusTimer.schedule(mLoginStatusTask, 0, 5000);
    }

    public void stopLoginStatus() {
        hideWaiting();
        if (mLoginStatusTimer != null) {
            mLoginStatusTimer.cancel();
            mLoginStatusTimer = null;
        }
        if (mLoginStatusTask != null) {
            mLoginStatusTask.cancel();
            mLoginStatusTask = null;
        }
    }

    private void updateByTimer() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mWaitingSeconds == 0) {
                    mBtnGetVerifyCode.setText("重发");
                    mBtnGetVerifyCode.setEnabled(true);
                    String phone = mEdtPhone.getText().toString().trim();
                    if(!TextUtils.isEmpty(phone) && phone.length() == 11) {
                        mBtnGetVerifyCode.setBackgroundResource(R.drawable.login_btn_border_red);
                    } else {
                        mBtnGetVerifyCode.setBackgroundResource(R.drawable.login_btn_border_gray);
                        mBtnGetVerifyCode.setEnabled(false);
                    }
                    mWaitingSeconds = WAITING_TIME;

                } else {
                    mBtnGetVerifyCode.setText(/*getString(R.string.getting_verifycode) +*/ mWaitingSeconds+"s");
                    mBtnGetVerifyCode.setBackgroundResource(R.drawable.login_btn_border_gray);
                    mWaitingSeconds--;
                    mBtnGetVerifyCode.setEnabled(false);
                    startTimer(1000);
                }
            }
        });
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    private void startTimer(int delay) {
        stopTimer();
        mTimer = new Timer("GET_VERIFYCODE");
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                updateByTimer();
            }
        };
        mTimer.schedule(mTimerTask, delay);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == SMS_LOGIN_REQ_CODE){
            mSmsLimit =  data.getStringExtra("smsLimit");
            String phone = data.getStringExtra("phone");
            if (phone != null){
                mEdtPhone.setText(phone);
            }
            mSmsChannel = data.getStringExtra("smsChannel");
            mSmsContent = data.getStringExtra("smsContent");
            showWaiting();
            SmsSender.send(Login.this, mSmsChannel, mSmsContent, new Action1<Integer>() {
                        @Override
                        public void run(Integer item) {
                            hideWaiting();
                            if (item == 1){
                                startLoginStatus();
                            }
                        }
                    });

        }
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            BestApp.getInstance().exit();
            super.onBackPressed();
        }
    }
}
